﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Routing;
using Microsoft.AspNet.Identity;
using System.Net.Http;
using ezCloud.Data;
using System.Net;
using System.Collections;

namespace ezCloud.Api.Common
{
    public class ApiAuthorize: AuthorizeAttribute
    {
        protected ezCloudDataContext Data { get; private set; }
        public static Dictionary<string, DateTime> onlineUsers = new Dictionary<string, DateTime>();

        public ApiAuthorize(ezCloudDataContext data)
        {
            this.Data = data;
        }

        public ApiAuthorize() 
            : this(new ezCloudDataContext())
        {
        }

        public override void OnAuthorization(HttpActionContext actionContext)
        {
            if (SkipAuthorization(actionContext))
            {
                return;
            }

            var userSessionManager = new UserSessionManager();
            if (userSessionManager.ReValidateSession())
            {
                /*if (onlineUsers.ContainsKey(userSessionManager.GetCurrentUserId()))
                {
                    onlineUsers[userSessionManager.GetCurrentUserId()] = DateTime.UtcNow;
                } else
                {
                    onlineUsers[userSessionManager.GetCurrentUserId()]  = DateTime.UtcNow;
                }*/
                base.OnAuthorization(actionContext);

            }
            else
            {
                actionContext.Response = actionContext.ControllerContext.Request.CreateErrorResponse(
                    HttpStatusCode.Unauthorized, "Session token expried or not valid.");
            }
        }

        private static bool SkipAuthorization(HttpActionContext actionContext)
        {
            return actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any()
                   || actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any();
        }
        protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
        {
               
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                //not in role
                actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Forbidden);
                actionContext.Response.Content = new StringContent("NOT_ENOUGH_PERMISSION");

            } else
            {
                actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
                actionContext.Response.Content = new StringContent("NOT_AUTHENTICATED");
            }
        }
    }
}